package com.netcracker.educenter.filestorage.servlets.files.downloading;

import com.netcracker.educenter.filestorage.configurator.Configurator;
import com.netcracker.educenter.filestorage.servlets.utils.FileUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@WebServlet(urlPatterns = "/user/Download")
public class DownloadFileServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(DownloadFileServlet.class);
    private static final String CONTENT_DISPOSITION_HEADER_KEY = "Content-Disposition";

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        String queryString = URLDecoder.decode(request.getQueryString(), "Cp1251");
        String fileName = queryString.substring(queryString.indexOf("=") + 1);

        String userName = (String)request.getSession().getAttribute("authorized_user");
        Path filePath = Paths.get(Configurator.getConfigurator().getPath()).resolve(userName).resolve(fileName);

        try (InputStream inputStream = Files.newInputStream(filePath);
             OutputStream outputStream = response.getOutputStream()) {

            ServletContext context = getServletContext();
            String mimeType = context.getMimeType(filePath.toString());
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }

            response.setContentType(mimeType);
            response.setContentLength((int) Files.size(filePath));

            String headerValue = String.format("attachment; filename=\"%s\"", FileUtils.rewriteFileNameToLatin(fileName));
            response.setHeader(CONTENT_DISPOSITION_HEADER_KEY, headerValue);

            byte[] buffer = new byte[4096];
            FileUtils.copy(inputStream, outputStream, buffer);

        } catch (IOException e) {
            log.error("download error", e);
        }
    }
}
